var ns, WXPhotoPicker,bmLocation, trans, db;
var app = new Vue({
    el: '#app',
    data: {
        ID: 0,
        form: {
            PatrolName: '',
            PatrolNumber: '',
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            CheckStatus: '1',
            TaskCompleteContent: '',
            GPSLocation: ''
        },
        PlanType: 3,
        imglist: [],
        maxuploadcount: CONFIG.maxuploadcount,
        planform: {},
        list: [],
        IsAllowWatermark: false,
        IsLoadWatermark:false,
    },
    methods: {
        get_data: function () {
            var that = this;
            that.get_data_frm();//获取任务信息
            that.get_data_file();//获取附件信息
        },
        get_data_frm: function () {
            var that = this;
            let selplantasksql = `SELECT * FROM Sys_PlanTask WHERE ID=${that.ID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: selplantasksql
            }, function (ret, err) {
                // console.log('SELECT-Sys_PlanTask')
                // console.log(JSON.stringify(ret))
                // console.log(JSON.stringify(err))
                if (ret.status) {
                    if (ret.data.length > 0) {
                        that.form = ret.data[0];
                        that.get_data_plan();
                        that.StartBmap();
                    }
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        get_data_file: function () {
            var that = this;
            let seltaskfilesql = `SELECT * FROM Sys_File WHERE TaskID=${that.ID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: seltaskfilesql
            }, function (ret, err) {
                // console.log('SELECT-Sys_File')
                // console.log(JSON.stringify(ret))
                // console.log(JSON.stringify(err))
                if (ret.status) {
                    that.imglist = ret.data;
                }
                // else {
                //     api.toast({
                //         msg: err,
                //         duration: 2000,
                //         location: 'bottom'
                //     });
                // }
            });
        },
        get_data_plan: function () {
            var that = this;
            let selplantasksql = `SELECT * FROM Sys_Plan WHERE ID=${that.form.PlanTaskID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: selplantasksql
            }, function (ret, err) {
                if (ret.status) {
                    if (ret.data.length > 0) {
                        that.planform = ret.data[0];
                        if (that.planform.ProjectID) {
                            that.getIsAllowWatermark(that.planform.ProjectID);//获取是否只调用相机权限
                        }
                    }
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
            let seltasksql = `SELECT * FROM Sys_PlanTask WHERE PlanTaskID=${that.form.PlanTaskID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: seltasksql
            }, function (ret, err) {
                if (ret.status) {
                    that.list = ret.data;
                }
            });
        },
        do_save: function () {
            var that = this;
            if (that.form.IsAllowUpload == 'true' && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.form.CheckStatus == '2') { //异常
                api.confirm({
                    title: '提示',
                    msg: '当前结果异常,是否需要上报异常记录?',
                    buttons: ['上报异常', '直接完成']
                }, function (ret, err) {
                    var ServiceStatus = -1;
                    if (ret.buttonIndex == 1) {
                        ServiceStatus = 1;
                    } else if (ret.buttonIndex == 2) {
                        ServiceStatus = 0;
                    }
                    if (ServiceStatus > -1) {
                        that.do_save_process(ServiceStatus);
                    }
                });
                return;
            }
            that.do_save_process(0);
        },
        reload_list: function () {
            api.sendEvent({
                name: 'reloadtaskoff',
            });
        },
        do_save_process: function (ServiceStatus) {
            var that = this;
            var nowDate = moment().format('YYYY-MM-DD HH:mm');
            //插入附件
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    let filesql = `INSERT INTO Sys_File (ID,TaskID,FilePath,PlanTaskID) VALUES (0,${that.ID},'${that.imglist[i].url}',${that.form.PlanTaskID});`;
                    db.executeSql({
                        name: 'prodemotest',
                        sql: filesql,
                    }, function (ret, err) {
                    });

                }
            }

            //判断是否按照巡更路线巡更 WithLine 0 否  1是
            if (that.planform.WithLine == '1') {
                //获取当前任务Index
                let result = that.list.findIndex((val) => {
                    return val.ID == that.ID;
                });
                //更新下一条任务
                if (result > -1 && (that.list.length - 1) != result) {
                    let nextform = that.list[result + 1];
                    let strnextsql = `UPDATE Sys_PlanTask SET CanPunchCard='true'  WHERE ID=${nextform.ID}`;
                    db.executeSql({
                        name: 'prodemotest',
                        sql: strnextsql
                    }, function (ret, err) {
                    });
                }

                //更新计划任务：当任务更新到第一条或最后一条时，更改状态
                if (result == 0) {
                    let strnextsql = `UPDATE Sys_Plan SET TaskStatus=2,TaskStatusDesc='执行中',CheckStartTime='${nowDate}'  WHERE ID=${that.form.PlanTaskID}`;
                    db.executeSql({
                        name: 'prodemotest',
                        sql: strnextsql
                    }, function (ret, err) {
                    });
                }
                 // //取消任务自动完成
                // if (result > -1 && (that.list.length - 1) == result) {
                //     let strnextsql = `UPDATE Sys_Plan SET TaskStatus=3,TaskStatusDesc='已完成',CheckEndTime='${nowDate}'  WHERE ID=${that.form.PlanTaskID}`;
                //     db.executeSql({
                //         name: 'prodemotest',
                //         sql: strnextsql
                //     }, function (ret, err) {
                //     });
                // }
            } else {
                //获取当前任务Index
                let result = that.list.findIndex((val) => {
                    return (val.TaskStatus == '1' || val.TaskStatus == '2') && val.ID != that.ID;
                });
                let resultIndex = that.list.findIndex((val) => {
                    return val.TaskStatus == '3';
                });

                //更新计划任务：当任务更新到第一条或最后一条时，更改状态
                if (resultIndex==-1) {
                    let strnextsql = `UPDATE Sys_Plan SET TaskStatus=2,TaskStatusDesc='执行中',CheckStartTime='${nowDate}'  WHERE ID=${that.form.PlanTaskID}`;
                    db.executeSql({
                        name: 'prodemotest',
                        sql: strnextsql
                    }, function (ret, err) {
                    });
                }
                 // //取消任务自动完成
                // if (result < 0) {
                //     let strnextsql = `UPDATE Sys_Plan SET TaskStatus=3,TaskStatusDesc='已完成',CheckEndTime='${nowDate}'  WHERE ID=${that.form.PlanTaskID}`;
                //     db.executeSql({
                //         name: 'prodemotest',
                //         sql: strnextsql
                //     }, function (ret, err) {
                //     });
                // }
            }

            //更新任务
            let newCheckStatus = that.form.CheckStatus == '1' ? 1 : 2;
            let newIsInvalidComplete = that.form.CheckStatus == '1' ? false : true;
            let newIsAllowCard = that.form.IsAllowCard == 'true' ? true : false;
            let username = api.getPrefs({ sync: true, key: 'username' });
            let headimg = api.getPrefs({ sync: true, key: 'headimg' });

            let strsql = `UPDATE Sys_PlanTask SET TaskStatus=3,APPUpload=1,IsMiss='false',CheckStatus=${newCheckStatus},IsInvalidComplete='${newIsInvalidComplete}',IsSupplementCard='${newIsAllowCard}',TaskCompleteContent='${that.form.TaskCompleteContent}',TaskCompleteTime='${nowDate}',GPSLocation='${that.form.GPSLocation}',TaskChargeManName='${username}',TaskChargeManHeaderImg='${headimg}' WHERE ID=${that.ID}`;
            db.executeSql({
                name: 'prodemotest',
                sql: strsql
            }, function (ret, err) {
                if (ret.status) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    that.reload_list();
                    if (ServiceStatus == 1) {
                        that.do_save_quality();
                    }
                    setTimeout(function () {
                        api.closeWin();
                    }, 1000)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });

        },
        //调用接口生成整改工单
        do_save_quality: function () {
            var that = this;
            let strsql = `UPDATE Sys_PlanTask SET IsAbnormal='true' WHERE ID=${that.ID}`;
            db.executeSql({
                name: 'prodemotest',
                sql: strsql
            }, function (ret, err) {
                if (ret.status) {
                    api.toast({
                        msg: '异常巡查记录已上报',
                        duration: 2000,
                        location: 'bottom'
                    });
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 3000,
                        location: 'bottom'
                    });
                }
            });
        },
        select_all_active: function (CheckStatus) {
            var that = this;
            if (that.planform.TaskStatus == '3' && that.form.IsAllowCard == 'false') {
                return;
            }
            that.form.CheckStatus = CheckStatus;
        },
        choose_picture: function () {
            var that = this;
            if(!that.IsLoadWatermark){
                return;
            }
            setTimeout(function(){
                ns.confirmPer('camera', function () {
                    if (that.IsAllowWatermark) {
                        that.upload_choose_picture();
                    }
                    else {
                        that.choose_picture_start();
                    }
                })
            },300); 
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.do_imageFilter(item.path);
                            // that.imglist.push({
                            //     ID: 0,
                            //     url: item.path,
                            //     thumbPath: item.path,
                            //     isupload: true
                            // });
                        });
                    }
                }
            });
        },
        remove_img: function (index,item) {
            var that = this;
            that.imglist.splice(index, 1);
            if (item.ID > 0 || item.ID != '' || item.ID != '0') {
                //先执行附件删除，再添加
                let delfilesql = `DELETE FROM Sys_File WHERE ID=${item.ID} AND TaskID=${item.TaskID} AND PlanTaskID=${item.PlanTaskID} `;
                db.executeSql({
                    name: 'prodemotest',
                    sql: delfilesql,
                }, function (ret, err) {
                });
            }
        },
        do_viewimages: function (activeIndex, IsLine) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (IsLine == 1) {
                    imageUrls.push(that.imglist[i].FilePath);
                }
                else {
                    imageUrls.push(that.imglist[i].url);
                }

            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        StartBmap: function () {
            var that = this;
            if (that.planform.TaskStatus == '3' && that.form.IsAllowCard == 'false') {
                return;
            }
            ns.confirmPer('location', function () {
                that.StartLocation();
            })
        },
        StartLocation: function () {
            var that = this;
            if (that.planform.TaskStatus == '3' && that.form.IsAllowCard == 'false') {
                return;
            }
            bmLocation.singleLocation({
                reGeocode: false,
                netWorkState: false
            }, function (ret) {
                // console.log(JSON.stringify(ret));
                if (ret.status) {
                    var locationDescribe=ns.DealLocationDescribe(ret.reGeo.locationDescribe);
                    that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber + locationDescribe;
                        // if (ret.reGeo.poiList != undefined && ret.reGeo.poiList.length > 0) {
                        //     that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        //         ret.reGeo.district + ret.reGeo.street + ret.reGeo.poiList[0].name;
                        // }
                }
            });
        },
        // 异常上报记录已分配-跳转到对应的工单
        onOpenOrder: function () {
            // var that = this;
            // //GongdanType  异常上报类型 1-维修工单 2-整改工单
            // //判断是报修工单还是整改工单
            // if(that.form.GongdanID&&that.form.GongdanType==1){
            //     ns.openWin('home_task_con_frm', '报修工单详情', {
            //         id: that.form.GongdanID,
            //     });
            // }
            // if(that.form.GongdanID&&that.form.GongdanType==2){
            //     ns.openWin('qualitycontroldetail_frm', '整改工单详情', {
            //         id:that.form.GongdanID,
            //     })
            // }
        },
        //获取是否只调用相机权限
        getIsAllowWatermark: function (ProjectID) {
            var that = this;
            let selconfigsql = `SELECT * FROM Sys_ProjectConfig WHERE ProjectID=${ProjectID} AND PlanType==3 AND ConfigKey='XGPhotoUse'`;
            that.IsLoadWatermark=false;
            db.selectSql({
                name: 'prodemotest',
                sql: selconfigsql
            }, function (ret, err) {
                that.IsLoadWatermark=true;
                if (ret.data.length > 0) {
                    let configdata = ret.data[0];
                    that.IsAllowWatermark = configdata.ConfigContent == '2' ? true : false;
                }
            });
        },
        // 系统只调用相机 并添加水印
        upload_choose_picture: function () {
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: that.IsAllowWatermark?false:true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    that.do_imageFilter(ret.data);
                    // if (that.IsAllowWatermark) {
                    //     that.waterMark(ret.data);
                    //     return;
                    // }
                    // else {
                    //     that.imglist.push({
                    //         ID: 0,
                    //         url: ret.data,
                    //         thumbPath: ret.data,
                    //         isupload: true
                    //     });
                    // }
                } 
            });
        },
        waterMark: function (imagePath) {
            var that = this;
            if (!imagePath) {
                api.toast({
                    msg: '图片地址为空',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            var imageName = imagePath.split('/').pop(); //获取图片名称
            var dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
            // 调用生成水印方法  返回Base64图片格式
            ns.setWatermark(imagePath, '安防巡更水印', dateTime, that.form.GPSLocation).then((value) => {
                var base64Str = value;
                if (base64Str) {
                    //Base64图片 转jpg、png格式
                    trans.saveImage({
                        base64Str: base64Str,
                        // album:true,
                        imgPath: "fs://watermark/",
                        imgName: imageName
                    }, function (ret, err) {
                        if (ret.status) {
                            var newImagePath = api.fsDir + '/' + 'watermark' + '/' + imageName;
                            that.imglist.push({
                                ID: 0,
                                url: newImagePath,
                                thumbPath: newImagePath,
                                isupload: true
                            });
                            //水印图片-保存到相册
                            api.saveMediaToAlbum({
                                path: 'fs://watermark/'+imageName
                            }, function(ret, err) {
                            });
                        } else {
                            api.toast({
                                msg: '水印图片保存本地失败！',
                                duration: 2000,
                                location: 'bottom'
                            });
                            return;
                        }
                    });
                } else {
                    // api.toast({
                    //     msg: '生成水印失败！',
                    //     duration: 2000,
                    //     location: 'bottom'
                    // });
                    that.imglist.push({
                        ID: 0,
                        url: imagePath,
                        thumbPath: imagePath,
                        isupload: true
                    });
                    return;
                }
            })
        },
         //图片压缩
         do_imageFilter:function(path){
            var that=this;
            var imgName = Date.now() + '.jpg';
            var target_w = 500;
            var imageFilter = api.require('imageFilter');
            imageFilter.getAttr({
                path: path
            }, function(ret, err) {
                if (ret.status) {
                    if (ret.width < target_w) {
                        target_w = ret.width;
                    }
                    var original_w = ret.width;
                    var original_h = ret.height;
                    var scale = original_w / target_w;
                    var target_h = Math.round(original_h / scale);
                    imageFilter.compress({
                        img: path,
                        quality: 1,
                        size: {
                            w: target_w,
                            h: target_h
                        },
                        save: {
                            album: false,
                            imgPath: api.cacheDir + '/upload/',
                            imgName: imgName
                        }
                    }, function(ret, err) {
                        if (ret.status) {
                            var imgFullName=api.cacheDir + '/upload/' + imgName;
                            if (that.IsAllowWatermark) {
                                that.waterMark(imgFullName);
                                return;
                            }
                            else {
                                that.imglist.push({
                                    ID: 0,
                                    url: imgFullName,
                                    thumbPath: imgFullName,
                                    isupload: true
                                });
                            }
                        }else{
                            alert( JSON.stringify( err ) );
                        }
                    });
                }
            });
        },
        configManager: function () {
            bmLocation.configManager({
                // accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
        },
    }
});
apiready = function () {
    api.parseTapmode();
    WXPhotoPicker = api.require('WXPhotoPicker');
    // 引入bmLocation定位
    bmLocation = api.require('bmLocation');
    trans = api.require('trans');
    ns = window.Foresight.Util;
    db = api.require('db');
    app.ID = api.pageParam.id || 0;
    toast = new auiToast();

    app.configManager();
    db.openDatabase({
        name: 'prodemotest'
    }, function (ret, err) {
        if (!ret.status) {
            api.toast({
                msg: err,
                duration: 2000,
                location: 'bottom'
            });
        }
        else {
            app.get_data();
        }
    });

    api.addEventListener({
        name: 'viewdisappear'
    }, function (ret, err) {
        bmLocation.stopLocation();//取消定位
    });

    bmLocation.setAgreePrivacy({
        agree: true
    });
}
